<?php
$module_instance = NULL;
function load_modules() {
	global $module_instance;
	if ($module_instance == NULL) 
		$module_instance = new CI_Module();
}
load_modules();
function module_instance() {
	global $module_instance;
	
	return $module_instance;
}

function load_widgets($position)  {
	global $module_instance; 
	$widgets = CI_Module::$_widgets;
	if (!isset($widgets[$position])) 
		return ;
	$widgets = $widgets[$position];
	if ($widgets) foreach ($widgets as $widget) {
		$mod_name = CI_Module::$_modules[$widget->MOD_ID]->MOD_NAME;
		$module_name = 'modules/'.$mod_name;
		$module_instance->load->model($module_name);
		$config = json_decode($widget->MPOS_CONFIG, true);
		$config ['widget_title']  = $widget->MPOS_TITLE;
		$config ['widget_id']  = $widget->MPOS_ID;
		$config ['widget_layout']  = $widget->MPOS_LAYOUT;
		$config ['widget_position']  = $widget->MPOS_POSITION;
		$module_instance->$mod_name->run($config);
	}
}
/**
 * @param string $position 
 * @param string $module_name 
 * @param boolean $pop if true, that wiget will be remove from wiget list;
 */
function get_widgets($position, $module_name = '', $pop = false)  {
	global $module_instance; 
	$widgets = CI_Module::$_widgets;
	if (!isset($widgets[$position])) 
		return ;
	$result = array();
	$widgets = $widgets[$position];
	if ($widgets) foreach ($widgets as $seq => $widget) {
		$widget->MOD_NAME = CI_Module::$_modules[$widget->MOD_ID]->MOD_NAME;
		if ($module_name && $widget->MOD_NAME != $module_name) {
			//Co $module_name thi chi lay cac widget cua module nay;
			continue;
		}
		$widget->MOD_CLASS = 'modules/'.$widget->MOD_NAME;
		$result [] = $widget;
		
		if ($pop) 
		unset(CI_Module::$_widgets[$position][$seq]);
	}
	return $result;
}

function load_widget($name, $config, $position = '') {
	global $module_instance;
	
}


function run_widget($mod_name, $widget) {
	global $module_instance;
	
	$module_name = 'modules/'.$mod_name;
	$module_instance->load->model($module_name);
	if (is_object($widget) && isset($widget->MPOS_CONFIG)) {
		$config = json_decode($widget->MPOS_CONFIG, true);
		$config ['widget_title']  = $widget->MPOS_TITLE;
		$config ['widget_id']  = $widget->MPOS_ID;
		$config ['widget_layout']  = $widget->MPOS_LAYOUT;
		$config ['widget_position']  = $widget->MPOS_POSITION;
	}else {
		$config =  $widget;
	}
	
	$module_instance->$mod_name->run($config);
}

function is_module_active($mod_name) {
	global $module_instance;
	return $module_instance->is_active_module($mod_name);
}

function is_widget_active($mod_name) {
	if (CI_Module::$_modules) foreach(CI_Module::$_modules as $module) {
		if ($mod_name == $module->MOD_NAME)
		return true;
	}
	return false;
}

function base_module_url($modulename = '', $action = '') {
	$url = base_url('/module/load') . '/';
	if ($modulename) 
		$url .= $modulename. '/';
	if ($action) 
		$url .= $action. '/';
	return $url;
}